//app.js
var loginUrl = require('./config').loginUrl;
var dishAllUrl = require('./config').dishAllUrl;
App({
  data: {
    uid: '',
    token: '',
    openid: '',
    wx_version: "", //微信版本号
    iPhone_vs: "",    //手机系统型号
    str_version: "",  // 版本号字符串
    animtedata:'',
    integral: '',   //用户积分
    category: '',
    markers: [{
      iconPath: "images/icon/others.png",
      id: 0,
      latitude: 29.544078,
      longitude: 106.511873
    }],
    dishList:{}
  },
  /**
  * 生命周期函数--监听小程序初始化
  */
  onLaunch: function () {
    var that = this;
    that.wxLogin();
    that.getDishList();
    wx.setStorageSync("Address", "not")
  },

  /**
   * 登录
   */
  wxLogin: function () {
    var that = this;
    wx.login({
      success: function (res) {
        that.getUserAuth(res.code);
      },
      fail: function (res) {
        if (wx.hideLoading) {
          wx.hideLoading();
        }
        wx.showModal({
          title: '提示',
          content: '登陆失败',
          showCancel: false,
          confirmText: "知道了",
          confirmColor: "#ffbe00",
        })
      }
    })
  },

  /**
     * 调用后台接口，传递code参数
     */
  sendAppCodeFunction: function (data) {
    var that = this;
    wx.request({
      url: loginUrl,
      method: "put",
      data: data,
      success: function (res) {
        if (res.data.code == 'ok') {
          wx.setStorageSync("skey", res.data.sessionKey);
        }
        else {
          that.showToast('未能正常获取', '');
        }
      },
      fail: function (error) {
        wx.showToast({
          title: '登录失败',
        })
      }
    })
  },

  /**
   * 弹框提示授权用户信息
   */
  getUserInfo: function (cb) {
    var that = this;
    if (wx.authorize) {
      wx.authorize({
        scope: 'scope.userInfo',
        success: function (res) {
          if (wx.showLoading) {
            wx.showLoading({
              title: '加载中',
              mask: true,
            })
          }
          that.getUserAuth(cd);
        },
        fail: function (res) {
          if (wx.openSetting) {
            wx.openSetting({
              success: function () {
                wx.authorize({
                  scope: 'scope.userInfo',
                  success: function () {
                    if (wx.showLoading) {
                      wx.showLoading({
                        title: '加载中',
                        mask: true,
                      })
                    }
                    that.getUserAuth(cd);
                  }
                })
              }
            })
          }
          else {
            that.getPhoneSysInfo();
          }
        }
      })
    }
    else {
      that.getPhoneSysInfo();
    }
  },

  /**
     * 得到授权获取用户信息
     */
  getUserAuth: function (cd) {
    var that = this;
    wx.getUserInfo({
      lang: "zh_CN",
      success: function (res) {
        wx.setStorageSync("userInfo", res.userInfo);
        wx.setStorageSync("authoriseUserInfo", true);
        // 设置用户昵称，头像
        that.data.value = res.userInfo.avatarUrl
        var data = {
          code:cd,
          encryptedData: res.encryptedData,
          iv: res.iv
        };
        that.sendAppCodeFunction(data);
      },
      fail: function (res) {
        if (wx.hideLoading) {
          wx.hideLoading();
        }
        //设置用户昵称，头像
        that.setData({
          avatarUrl: "../../img/airfit.png",
        })
      }
    })

  },

  /**
   * 获取设备信息 
   */
  getSystemInfo: function () {
    var that = this;
    var contentWidth = "";
    var contentHeight = "";
    var modelName = "";
    wx.getSystemInfo({
      success: function (res) {
        modelName = res.model;
        contentHeight = res.windowHeight;
        contentWidth = res.windowWidth;
      },
    })
    var appObj = { mob_width: contentWidth, mob_height: contentHeight, mob_name: modelName };
    return appObj;
  },

  /**
    * 获取系统信息
    @wx_version:微信版本号
    @iPhone_vs:手机版本
    */
  getPhoneSysInfo: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        var v1 = res.version.split(".");
        var v2 = v1[0] + v1[1] + v1[2];
        var spsys = res.system.split(' ');
        if (spsys[0] === 'Android') {
          //安卓版本下于6.5.8，提示不支持
          if (v1[0] <= 6 && v1[1] <= 5 && v1[2] <= 8) {
            that.data.wx_version = v2;
            that.data.iPhone_vs = spsys[0];
            that.data.str_version = res.version;
            that.userAuthorizeJianRong();
          }
        }
        else {
          //ios版本小于 6.5.10，提示不支持
          if (v1[0] <= 6 && v1[1] <= 5 && v1[2] <= 10) {
            that.data.wx_version = v2;
            that.data.iPhone_vs = spsys[0];
            that.data.str_version = res.version;
            that.userAuthorizeJianRong();
          }
        }
      },
    })
  },

  /**
     * 用户授权兼容性 处理方法
     * @str_version:微信版本号
     */
  userAuthorizeJianRong: function () {
    wx.showModal({
      title: '提示',
      showCancel: false,
      confirmText: "知道了",
      confirmColor: "#555",
      content: '您当前的微信版本(' + this.data.str_version + ')过低，可能会出现不兼容问题，请升级到最新版本微信，谢谢。'
    })
  },


  /**
   * 全局模态框 提示方法
   * @titles:模态框标题
   * @tiptext:模态框提示内容
   */
  GBshowModalTip: function (title,showCancel, tiptext, successFun) {
    wx.showModal({
      title: title,
      showCancel: showCancel,
      content: tiptext,
      confirmText: '确定',
      confirmColor: "#555",
      success: successFun
    })
  },

  /**
   * 全局提示 showToast
   * @title:提示内容
   * @icon:提示框icon
   */
  showToast: function (title, img,time) {
    wx.showToast({
      image: img,
      title: title,
      duration: time
    })
  },

  /**
   * 隐藏加载提示
   */
  hideLoading: function () {
    if (wx.hideLoading) {
      wx.hideLoading();
    }
  },
  /**
   *全局模态框 showToast
   * @title:提示内容
   */
  showModal:function(title,content){
    if(wx.showModal){
      wx.showModal({
        title: title,
        content: content,
      })
    }
  },
  /**
   *  选择本地图片，添加头像 
   */
  chooseImage: function (res) {
    var that = this;
    if (wx.chooseImage) {
      wx.chooseImage({
        success: function (res) {
          var tempFiles = res.tempFiles;
          if (!tempFiles) {
            app.getPhoneSysInfo();
          }
          else {
            //单张图片 1M以内  （1M=1024KB  1Kb=1024B）
            var sizeRule = 1024 * 1024;
            var imgSize = tempFiles[0].size;
            if (imgSize > sizeRule) {
              wx.showModal({
                title: '提示',
                content: '请添加1M以内的图片',
                showCancel: false,
                confirmText: "知道了",
                confirmColor: "#ffbe00",
              })
            }
            else {
              that.setData({
                userimg: tempFiles[0].path
              })
            }
          }
        },
        fail: function () {

        }
      })
    }
    else {
      app.getPhoneSysInfo();
    }
  },
  // 页面跳转
  pageTurns: function (url) {
    // wx.switchTab({
    //    url: url,
    // })
    wx.navigateTo({
      url: url,
    })
  },

  // 初始化所以商品
  getDishList:function(){
    var that = this;
    wx.request({
      url: dishAllUrl,
      method: 'get',
      data: {},
      success: function (res) {
        var dishList = res.data.dishList;
        var temp;
        for (var i = 0; i < dishList.length - 1; i++) {
          for (var j = 0; j < dishList.length - 1 - i; j++) {
            if (dishList[j].dish.saleNum < dishList[j+1].dish.saleNum ) {
              temp = dishList[j];
              dishList[j] = dishList[j + 1];
              dishList[j + 1] = temp;
            }
          }
        }
        for (var i = 0; i < dishList.length; i++) {
          var imgList = dishList[i].img;
          dishList[i].banner = [];
          dishList[i].info = [];
          for (var j = 0; j < imgList.length; j++) {
            if (imgList[j].imgType === 1) {
              dishList[i].icon = imgList[j].imgUrl;
            }
            if (imgList[j].imgType === 2) {
              var banner = dishList[i].banner;
              banner.push(imgList[j].imgUrl);
            }
            if (imgList[j].imgType === 3) {
              dishList[i].sign = imgList[j].imgUrl;
            }
            
            if (imgList[j].imgType === 4) {
              
              var info = dishList[i].info;
              info.push(imgList[j].imgUrl);
            }
          }
        }
        that.data.dishList = dishList;
      }
    })
  }
})
